package cn.zzuisa.news.filter;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zzuisa.news.enums.FilterEnums;
import cn.zzuisa.news.util.JsonUtil;
import cn.zzuisa.news.util.ResultVOUtil;

/**
 * @ClassName: LoginFilter.java
 * @Description: 登录拦截器
 * @author zzuisa
 * @version V1.0
 * @Date 2018年9月4日 下午8:33:17
 */
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		System.out.println("拦截器开始工作---:" + req.getSession().getAttribute("user"));
		if (req.getSession().getAttribute("user") == null) {
			String XRequested = req.getHeader("X-Requested-With");
			/*判断是否是Ajax请求*/
			if ("XMLHttpRequest".equals(XRequested)) {
				resp.getWriter().println(JsonUtil.setData(ResultVOUtil.failed(FilterEnums.FILTER_MSG)));
			} else {
				System.out.println("拦截:" + req.getSession().getAttribute("user"));
				req.getRequestDispatcher("WEB-INF/ftl/user/login.ftl").forward(req, resp);
			}
			return;
		}
		System.out.println("放行:" + req.getSession().getAttribute("user"));
		filterChain.doFilter(request, response);

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
